<template>
  <div style="display: flex; justify-content: center;">
    <div :id="id" :class="className" :style="{height:height+'px',width:width}" />
    <div class="control" style="width: 30%;">
      <div class="legend mt16">
        <div
          class="card flex-h-sb flex-v-center"
          v-for="(item, i) in series_obj1"
          :key="i"
        >
          <div class="left tof flex-v-center">
            <el-checkbox
              style="margin: 2px 5px 0 14px;"
              class="flex-v-center"
              v-model="item.status"
              @change="legendHandle(item.key)"
            ></el-checkbox>
            <div class="legend-name tof">
              {{ item.name }}
            </div>
          </div>
        </div>
        <div class="fillcard"></div>
      </div>
      <div class="showAll">
        <el-button size="small" @click="lineEcahrtsShowAllHandle">
          {{ lineEcahrts_showAll ? '取消全选' : '全部勾选' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '../mixins/resize'
import { getSubInvestInfoLineByCompositionId } from '@/api/afterInvest'
import { upFixed, downFixed, parseTime } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    ids: {
      type: String | Number,
      required: true
    },
    id_index: {
      type: Array,
      default: () => {
        return []
      }
    },
    dates: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null,
      startTime: '',
      endTime: '',
      xDate: [], // y轴
      fitNetWorth_obj: {}, // 拟合
      netWorth_obj: {}, // 净值
      contrastIndex_obj: {}, // 指数
      series_obj1: [],
      legendStatus: {},
      chart_option: {},
      lineEcahrts_showAll: true,

    }
  },
  watch: {
    ids: {
      handler(id) {
        if(id) this.initPage()
      },
      deep: true,
      immediate: true
    },
    id_index: {
      handler(id) {
        // if(this.startTime&&this.endTime) {
        //   this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, id)
        // }else {
        //   setTimeout(() => {
        //     this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, id)
        //   }, 1000)
        // }
        this.initPage()
      },
      deep: true
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initPage() {
      Promise.all([this.getSubInvestInfoLineByCompositionId(this.ids)]).then(res => {
        console.log('曲线:', res)
        const list = res[0].body
        if(list&&list.length>0) {
          // const base_incomeRate_drawDown_list = []
          // const base_netWorth_drawDown_list = []
          const base_netWorth = []
          list.forEach((items, index) => {
            this.xDate.push(parseTime(items.date))
            items.item.map((el, i) => {
              // if(index==0) base_netWorth[i] = el.netWorth - 1 // 改作不归1
              if(index==0) base_netWorth[i] = 0
              el.pnl = el.pnl ? Number(el.pnl) : 0
              if(!this.fitNetWorth_obj[el.key]) this.fitNetWorth_obj[el.key] = []
              // if(!this.netWorth_obj[el.key]) this.netWorth_obj[el.key] = []
              
              if(el.netWorth!=null) {
                const val = (el.netWorth - base_netWorth[i]).toFixed(4)
                this.fitNetWorth_obj[el.key].push(val)
              }else {
                this.fitNetWorth_obj[el.key].push(null)
              }
              // if(el.key=="ztz-wy-1") console.log(this.fitNetWorth_obj);
              // if(el.netWorth == null) {
              //   this.netWorth_obj[el.key][index] = null
              // }else if(Number(el.netWorth)<Number(base_incomeRate_drawDown_list[i])) {
              //   if(el.isIndex) {
              //     this.netWorth_obj[el.key][index] = (((el.netWorth-base_incomeRate_drawDown_list[i])/(Number(base_incomeRate_drawDown_list[i])+100))*100).toFixed(2)
              //   }else {
              //     this.netWorth_obj[el.key][index] = (el.netWorth-base_incomeRate_drawDown_list[i]).toFixed(2)
              //   }
              // }else {
              //   base_incomeRate_drawDown_list[i] = el.netWorth
              //   base_netWorth_drawDown_list[i] = el.netWorth / 100 + 1
              //   this.netWorth_obj[el.key][index] = 0
              // }
            })
          })
        }
        this.$nextTick(() => {
          this.chart && this.chart.dispose()
          this.initChart(this.fitNetWorth_obj)
        })
      })
    },
    initChart(obj1) {
      this.chart = echarts.init(document.getElementById(this.id))
      // this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      const color_list = [
        'rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)',
        '#cca4e3','#96ce54','#ff4777','#1685a9','#eedeb0','#0aa344','#f00056','#4b5cc4','#e29c45', 'rgba(238,203,87,1)',
        '#21a675','#f9906f','#44cef6','#ae7000','#057748','#f05654','#a1afc9','#a78e44','#00e500','#c93756','#065279','#d9b611',
        '#9b4400','#00e09e','#8c4356','#3b2e7e','#7fecad','#f20c00','#426666','#827100','#a4e2c6','#9d2933','#815476',
        '#6e511e','#0eb83a','#b36d61','#edd1d8','#48c0a3','#bf242a','#4c221b','#549688','#60281e','#003371','#789262',
        '#ff7500','#801dae','#758a99','#ffa631','#4c8dae','#50616d','#b0a4e3','#424c50','#fff143','#bce672'
      ]
      this.series_obj1 = []

      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          const item = obj1[key]
          this.series_obj1.push({
            key: key,
            name: key,
            status: true,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            data: item,
            connectNulls: true
          })
        })
      }

      this.chart_option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}</span>
                      </div>`
              }else {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> --</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '15%',
          left: '7%',
          right: '5%',
          bottom: '20%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false,
          right: '20',
          top: '2%',
          type: 'scroll',
          textStyle: {
            color: '#90979c'
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto'
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          brushSelect: false,
          realtime: true, // 实时更新系列的视图
          height: '6%',
          bottom: '5%',
        }],
        series: this.series_obj1
      }
      this.chart.setOption(this.chart_option)
    

      // this.chart.on('datazoom', () => {
      //   const op = this.chart.getOption()
      //   // const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
      //   const list = this.xReturnZero(this.fitNetWorth_obj)

      //   Object.keys(list).forEach((key, index) => {
      //     const item = list[key]
      //     const i = op.series.findIndex(os => os.name==key)
      //     if(i!=-1) {
      //       op.series[i].data = item
      //     }
      //   })
      //   this.chart.setOption(op)
      // })
    },

    
    xReturnZero() {
      const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
      const res = []
      const base_netWorth = []
      Object.keys(this.fitNetWorth_obj).forEach((key, index) => {
        const items = this.fitNetWorth_obj[key]
        res[key] = []
        items.forEach((item, i) => {
          if(i==0) base_netWorth[index] = items[baseline_i] - 1
          if(item!=null) {
            const val = (item - base_netWorth[index]).toFixed(4)
            res[key].push(val)
          }else {
            res[key].push(null)
          }
        })
      })
      return res
    },

    getSubInvestInfoLineByCompositionId(compositionId) {
      return new Promise(resolve => {
        getSubInvestInfoLineByCompositionId({
          compositionId, 
          startTime: this.dates[0],
          endTime: this.dates[1],
          indexTypes: this.id_index
        }).then(res => {
          console.log('投后净值:', res)
          resolve(res)
        })
      })
    },
    legendHandle(key) {
      this.chart.dispatchAction({
        type: 'legendToggleSelect',
        name: key
      })
    },
    lineEcahrtsShowAllHandle() {
      this.lineEcahrts_showAll = !this.lineEcahrts_showAll
      this.series_obj1.map(item => { 
        this.legendStatus[item.key] = this.lineEcahrts_showAll
        item.status = this.lineEcahrts_showAll
      })
      this.chart.setOption(this.chart_option)
    },
  }
}
</script>
<style lang="scss" scoped>
.control {
  position: relative;
  width: 432px;
  display: flex;
  flex-direction: column;
  margin-left: 24px;
  height: 380px;
  .beyondIncome {
    .shortline {
      width: 20px;
      border: 1px solid #d9d9d9;
    }
  }
  .showReal {
    padding: 0 13px 0 14px;
  }
  .legend {
    // margin-top: 15px;
    min-width: 432px;
    height: 100%;
    overflow: auto;
    background: #fafafa;
    border-radius: 8px;
    .card {
      height: 48px;
      cursor: pointer;
      padding: 0 13px 0 14px;
      box-shadow: inset 0px -1px 0px 0px #f0f0f0;
      &:hover {
        background: #ffffff;
        box-shadow: inset 0px -1px 0px 0px #f0f0f0;
      }
      .left {
        width: 240px;
      }
      .right {
        width: 150px;
        font-size: 12px;
        color: #8c8c8c;
        p {
          text-align: right;
        }
      }
      .legend-name {
        .line {
          width: 28px;
          margin-left: 6px;
        }
      }
    }
  }
  .legend-name {
    .line {
      width: 28px;
      margin-left: 6px;
    }
  }
  .mt16 {
    margin-top: 16px;
  }
  .icon-zhihuan {
    color: #1890ff;
    cursor: pointer;
  }
  .fillcard {
    height: 48px;
  }
  .showAll {
    width: 99.8%;
    line-height: 48px;
    background: rgba(166, 166, 166, 0.4);
    border-radius: 0px 0px 8px 8px;
    position: absolute;
    bottom: 0;
    text-align: center;
    margin: 0 auto;
  }
}
</style>

